package com.microservice.salmon.web.handler;

import com.microservice.salmon.service.exception.ResourceException;
import com.salmon.common.ApiResponse;
import com.salmon.common.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 统一异常处理
 * </p>
 *
 * @author 王洪庆 2019-01-14 17:10
 */
@ControllerAdvice
public class ResourceExceptionHandler {

    /**
     * 实体验证,当controller中对应的方法加入@Valid注解后，走这个异常信息
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseEntity<ApiResponse> handleBindException(BindException ex, HttpServletRequest request) {
        HttpStatus status = WebUtils.getStatus(new ServletWebRequest(request));
        List<ObjectError> objectErrorList = ex.getAllErrors();
        StringBuilder error = new StringBuilder();
        objectErrorList.forEach(objectError -> {
            if(error.length() > 0)
                error.append(" || ");
            error.append(objectError.getDefaultMessage());
        });
        ApiResponse apiResponse = ApiResponse.ofMessage(status.value(), error.toString());
        return new ResponseEntity<>(apiResponse, status);
    }


    @ExceptionHandler(ResourceException.class)
    @ResponseBody
    public ResponseEntity<ApiResponse> handleResourceException(ResourceException ex, HttpServletRequest request) {
        HttpStatus status = WebUtils.getStatus(new ServletWebRequest(request));
        ApiResponse apiResponse = ApiResponse.ofMessage(ex.getCode(), ex.getMessage());
        return new ResponseEntity<>(apiResponse, status);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<ApiResponse> handleSystemException(Exception ex, HttpServletRequest request) {
        HttpStatus status = WebUtils.getStatus(new ServletWebRequest(request));
        ApiResponse apiResponse = ApiResponse.ofMessage(status.value(), ex.getMessage());
        return new ResponseEntity<>(apiResponse, status);
    }
}
